package cn.com.cetccst.mdmdemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zdk.mg.agent.R;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import cn.com.cetccst.mdmdemo.utils.ToolbarActivity;

public class AppListActivity extends ToolbarActivity {
    public static final int kTypeApp = 1;
    public static final int kTypeNet = 2;
    public static final int kTypeSilentUninstall = 3;
    public static final int kTypeCanInstallApk = 4;
    public static final int kTypeSuperApp = 5;
    public static final int kTypeKeepAlive = 6;
    public static final int kTypeUnknownSource = 7;
    public static final int kTypeInstallBlocked = 8;
    public static final int kTypeUninstallBlocked = 9;

    public static final Type listType = new TypeToken<List<String>>() {
    }.getType();

    private static final String[] typeStrs = {
            "", "应用黑名单", "网络白名单", "静默卸载应用", "安装源应用", "特权应用", "保活应用",
            "设置未知来源应用", "禁止安装应用", "禁止卸载应用"
    };

    private int type;
    private List<Item> packageNameList = new ArrayList<>();
    private List<String> selectedApps;
    private ListAdapter listAdapter;
    private ListView listView;

    public static void show(Activity activity, int type, List<String> apps, int requestCode) {
        Intent intent = new Intent(activity, AppListActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("apps", apps == null ? "" : new Gson().toJson(apps));
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_list);
        type = getIntent().getIntExtra("type", -1);
        selectedApps = new Gson().fromJson(getIntent().getStringExtra("apps"), listType);
        if (selectedApps == null) {
            selectedApps = new ArrayList<>();
        }
        initToolbar(typeStrs[type]);

        listAdapter = new ListAdapter(this);
        listView = findViewById(R.id.appInfos);
        listView.setAdapter(listAdapter);
        getAppList();
    }

    private void getAppList() {
        packageNameList.clear();
        final PackageManager packageManager = getPackageManager();
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        String selfPackageName = getPackageName();
        // get all apps
        final List<ResolveInfo> rinfo = packageManager.queryIntentActivities(mainIntent, 0);
        for (ResolveInfo app : rinfo) {
            if (type == kTypeApp && app.activityInfo.packageName.equals(selfPackageName)) {
                continue;
            }
            packageNameList.add(new Item(app.activityInfo.packageName, selectedApps.contains(app.activityInfo.packageName)));
        }

        packageNameList.sort(new Comparator<Item>() {
            @Override
            public int compare(Item item, Item t1) {
                return t1.checked ? 1 : -1;
            }
        });
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.app_list_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.ok) {
            List<String> retPackageNames = new ArrayList<>();
            for (Item pkgItem : packageNameList) {
                if (pkgItem.checked) {
                    retPackageNames.add(pkgItem.packageName);
                }
            }
            Intent intent = new Intent();
            intent.putExtra("apps", new Gson().toJson(retPackageNames));
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private static class Item {
        public String packageName;
        public boolean checked;

        public Item(String packageName, boolean checked) {
            this.packageName = packageName;
            this.checked = checked;
        }
    }

    private final class ListAdapter extends BaseAdapter {
        private Context context;

        public ListAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return packageNameList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            View view = View.inflate(context, R.layout.app_info_item, null);
            fillItem(view, packageNameList.get(i));
            return view;
        }

        private void fillItem(View listItem, Item item) {
            try {
                PackageManager packageManager = context.getApplicationContext().getPackageManager();
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(item.packageName, 0);
                Drawable drawable = packageManager.getApplicationIcon(applicationInfo);
                ImageView appIcon = listItem.findViewById(R.id.appIcon);
                appIcon.setImageDrawable(drawable);

                String label = packageManager.getApplicationLabel(applicationInfo).toString();
                setTextViewText(listItem, R.id.appName, label);
                setTextViewText(listItem, R.id.pkgName, item.packageName);

                CheckBox checkBox = listItem.findViewById(R.id.checkBox);
                checkBox.setChecked(item.checked);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                        item.checked = checked;
                    }
                });
            } catch (PackageManager.NameNotFoundException e) {

            }
        }

        private void setTextViewText(View item, int resId, String text) {
            TextView textView = item.findViewById(resId);
            textView.setText(text);
        }
    }
}